package com.kkks.spring_rest.tick.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kkks.spring_rest.tick.model.WhoUsers;
import com.kkks.spring_rest.tick.service.UserService;

@Controller
@RequestMapping("/UserController")
public class UserController {

	@Autowired
	private UserService userService;

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	@RequestMapping(value = "/list.do", method = RequestMethod.GET)
	public String list(Model model) throws Exception {
		model.addAttribute("userList", userService.getAllUsers());
		return "user/list";
	}

	@RequestMapping(value = "/popWindow", method = RequestMethod.GET)
	public String popWindow() throws Exception {
		return "user/popWindow";
	}

	@RequestMapping(value = "/addOrUpdate", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, String> addOrUpdate(WhoUsers user) {
		// spring会利用jackson自动将返回值封装成JSON对象
		Map<String, String> map = new HashMap<String, String>();
		try {
			userService.addOrUpdate(user);
			map.put("returnValue", "操作成功");
		} catch (Exception e) {
			e.printStackTrace();
			map.put("returnValue", "操作失败");
		}
		return map;
	}

	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, String> delete(@RequestParam("uid") List<Integer> usersId) {
		// spring mvc 还可以将参数绑定为list类型
		Map<String, String> map = new HashMap<String, String>();
		try {
			userService.deleteUsers(usersId);
			map.put("returnValue", "删除成功");
		} catch (Exception e) {
			e.printStackTrace();
			map.put("returnValue", "删除失败");
		}
		return map;// 重定向
	}
}
